package com.base.test.dao.transaction;

import org.apache.shardingsphere.api.hint.HintManager;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;

import javax.sql.DataSource;

/**
 * 事务处理：事务中，强制读主库
 */
public class ShardingDataSourceTransactionManager extends DataSourceTransactionManager {
        private static final long serialVersionUID = -1459584315029874109L;

        public ShardingDataSourceTransactionManager(DataSource dataSource) {
            super(dataSource);
        }

        @Override
        protected void doBegin(Object transaction, TransactionDefinition definition) {
            if (!HintManager.isMasterRouteOnly()) {
                HintManager hintManager = HintManager.getInstance();
                hintManager.setMasterRouteOnly();
            }
            super.doBegin(transaction, definition);
        }

        @Override
        protected void doResume(Object transaction, Object suspendedResources) {
            if (!HintManager.isMasterRouteOnly()) {
                HintManager hintManager = HintManager.getInstance();
                hintManager.setMasterRouteOnly();
            }
            super.doResume(transaction, suspendedResources);
        }

        @Override
        protected Object doSuspend(Object transaction) {
            HintManager.clear();
            return super.doSuspend(transaction);
        }

        @Override
        protected void doCleanupAfterCompletion(Object transaction) {
            HintManager.clear();
            super.doCleanupAfterCompletion(transaction);
        }
    }